package com.xjtu.se.homework.ops.feedback.impl;

import com.xjtu.se.homework.common.Result;
import com.xjtu.se.homework.common.Utils;
import com.xjtu.se.homework.common.page.QueryAction;
import com.xjtu.se.homework.ops.faq.dao.FaqDao;
import com.xjtu.se.homework.ops.feedback.EmailDto;
import com.xjtu.se.homework.ops.feedback.FeedBackDto;
import com.xjtu.se.homework.ops.feedback.FeedBackService;
import com.xjtu.se.homework.ops.feedback.dao.FbDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

@Service
@Transactional
public class FeedBackServiceImpl implements FeedBackService {
    @Resource
    private FbDao fbDao;
    @Override
    public Map<String, Object> getAllFbs(FeedBackDto dto) {
        class MyAction implements QueryAction<FeedBackDto> {

            @Override
            public List<FeedBackDto> execute() {
                List<FeedBackDto> fbList= fbDao.showAll(dto);
                for (FeedBackDto fb:fbList) {
                    if(fb.getF_image()!=null){
                        String regex = ",";
                        String strAry[] = fb.getF_image().split(regex);
                        ArrayList<String> imageAry = new ArrayList<String>();
                        for (String str : strAry) {
                            System.out.println("D:/project/homework_helper/helper-springboot/uploads/" + str);
                            String search_image = "D:/project/homework_helper/helper-springboot/uploads/" + str;
                            FileInputStream in = null;
                            ByteArrayOutputStream bos = null;
                            try {
                                File file = new File(search_image);
                                if (!file.exists()) {
                                    throw new Exception("图片不存在");
                                }
                                in = new FileInputStream(search_image);
                                bos = new ByteArrayOutputStream();
                                byte[] b = new byte[1024];
                                int len = -1;
                                while ((len = in.read(b)) != -1) {
                                    bos.write(b, 0, len);
                                }
                                byte[] fileByte = bos.toByteArray();
                                Base64.Encoder encoder = Base64.getEncoder();
                                String image = encoder.encodeToString(fileByte);
                                imageAry.add(image);
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                try {
                                    in.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        fb.setImageAry(imageAry);
                    }
                }
                return fbList;
            }
        }
        Map<String, Object> page =Utils.getPage(dto, new MyAction());
        return page;

    }
//        Map<String, Object> page = Utils.getPage(dto, () -> fbDao.showAll(dto));
//        return page;
//    }

    @Override
    public Result sendEmail(EmailDto emailDto) {
        try {
            sendmail(emailDto.getU_email(),emailDto.getF_back());
        } catch (Exception e) {
            return Result.fail(500,"邮件发送失败！！");
        }
        fbDao.updateStatus(emailDto.getF_id());
        return Result.success("邮件发送成功！！");
    }
    //发送邮件方法
    public  void sendmail(String address,String f_back) throws Exception{

        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");
        //使用JavaMail发送邮件的5个步骤
        //1、创建session
        Session session = Session.getInstance(prop);
        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);
        //2、通过session得到transport对象
        Transport ts = session.getTransport();
        //3、连上邮件服务器.使用邮箱的用户名和密码连上邮件服务器，发送邮件时，
        // 发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和密码都通过验证之后才能够正常发送邮件给收件人
        ts.connect("smtp.qq.com", "2698390953@qq.com", "ajyqozbltyifdgie");
        //4、创建邮件
        Message message = createMail(session,address,f_back);
        //5、发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    }
    public static MimeMessage createMail(Session session, String address, String f_back) throws Exception {
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress("2698390953@qq.com"));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
        //邮件的标题
        message.setSubject("对您提出问题的回答");
        //邮件的文本内容
        message.setContent(f_back, "text/html;charset=UTF-8");
        //返回创建好的邮件对象
        return message;
    }
}
